#!/usr/bin/perl

use strict;
use lib '../trunk';
use WWW::Metaweb;
use WWW::Metaweb::JSONLikePerl qw(:standard);

# Used to view a Perl object response, also the most useful module - ever.
use Data::Dumper;

=head1 NAME

json_preprocessor.pl - Demonstrates how to use the JSON pre-processor hook for WWW::Metaweb

=head1 SYNOPSIS

perl json-preprocessor.pl

=head1 DESCRIPTION

This script gives an example of using a JSON preprocessor callback, in this case the callback just inserts another property query at the beginning of each query it is passed to get the creator (from /type/object).

It's possible to set multiple pre-processors by setting the json_preprocessor attribute to an array reference of sub-routine references they will be called in array order, for instance:

  $mh->{json_preprocessor} = [ \&pre_pre_processor, \&pre_processor ];

This would cause each query to be processed by these two sub-routines before being sent to Metaweb. The equivilant of:

  $json = pre_pre_processor($json);
  $json = pre_processor($json);

If you've got any questions about stuff here, please feel free to email me:
hds (at) caffeineconcepts.com

=cut

sub preprocess  {
	my $json = shift;
	my $new_json;

	$new_json = jsonlp_quote('->{query}->{season}', $json, '"');

	print "<<$new_json>>\n";

	return $new_json || $json;
}

sub cursor_preprocess  {
	my $json = shift;

	unless ($json =~ /"cursor":.+?[,\}]/)  {
		$json =~ s/^{/{"cursor":true,/;
	}

	return $json;
}

my $mh = WWW::Metaweb->connect( server => 'www.freebase.com',
                                auth_uri => '/api/account/login',
                                read_uri => '/api/service/mqlread',
				write_uri => '/api/service/mqlwrite',
				trans_uri => '/api/trans',
				json_preprocessor => [\&preprocess,
						      \&cursor_preprocess],
				pretty_json => 1 );

my ($query, $json, $res);

$json = {
	league => 'DSFLL',
	season => '2007', # quotes don't actually work in conversion...
	name => undef,
	type => '/user/szaijan/fantasy_football/scoring',
	rule => [{
		activity => undef,
		points => undef,
		unit => undef
	}]
};

$query = {
	#cursor => JSON::True,
	query => {
		name => "Nico Minoru",
		type => [],
		guid => undef
	}
};

#$query = { name => 'Nico Minoru', type => [], guid => undef };
#my ($res1, $res2) = $mh->read($query, $json);

#print $WWW::Metaweb::errstr . "\n";

#print Dumper $res1;

print $mh->read($json);
print $WWW::Metaweb::errstr . "\n";

exit;
